#!/usr/bin/env node

// const program = require('commander')

// program
//   .version(require('../package').version, '-v, --version')
//   .option('--verbose', 'Print a
// formatted string of the compilation information (similar to CLI output).')
//   .parse(process.argv)

// require('../lib/build')(program)

import path from 'path'
import glob from 'glob'
import { spawnSync } from 'child_process'

import { logger } from './utils'

const [executor, bin, script, ...args] = process.argv

function getEnv() {
  return Object.keys(process.env)
    .filter(key => process.env[key] !== undefined)
    .reduce(
      (envAcc, key) => ({
        ...envAcc,
        [key]: process.env[key],
      }),
      {},
    )
}

function spawnSyncScript() {
  const relativeScriptPath = path.join(__dirname, './scripts', script)
  const scriptPath = require.resolve(relativeScriptPath)

  if (!scriptPath) {
    throw new Error(`Unknown script "${script}".`)
  }

  const result = spawnSync(executor, [scriptPath, ...args], {
    stdio: 'inherit',
    env: getEnv(),
  })

  if (result.signal) {
    process.exit(1)
  } else {
    process.exit(result.status)
  }
}

if (!script) {
  const scriptsPath = path.join(__dirname, 'scripts/')
  const scriptsAvailable = glob.sync(path.join(__dirname, 'scripts', '*'))
  const scriptsAvailableMessage = scriptsAvailable
    .map(s => s.replace(scriptsPath, '').replace(/\.js$/, ''))
    .join('\n  ')
    .trim()

  const fullMessage = `
Usage: ${bin} [script] [--options]
Available Scripts:
  ${scriptsAvailableMessage}
  `.trim()
  console.log(`\n${fullMessage}\n`) // eslint-disable-line
} else {
  spawnSyncScript()
}

process.on('unhandledRejection', error => {
  logger.error('unhandledRejection', error.message)
})
